﻿namespace PreGUI.Helpers
{
    using UnityEngine;
    using UnityEngine.EventSystems;

    /// <summary>
    /// Adds the ability to drag a component via the mouse.
    /// </summary>
    public class PGDraggable : MonoBehaviour, IDragHandler
    {
        public GameObject Target = null;
        RectTransform _mTransform;

        // Use this for initialization
        void Start()
        {
            _mTransform = Target.GetComponent<RectTransform>();
            _mTransform.pivot = new Vector2(0f, 0f);
        }

        public void OnDrag(PointerEventData eventData)
        {
            _mTransform.SetAsLastSibling();
            _mTransform.position += new Vector3(eventData.delta.x, eventData.delta.y);
            _mTransform.position = new Vector3
                (
                Mathf.Min(Screen.width - _mTransform.sizeDelta.x, Mathf.Max(0f, _mTransform.position.x)),
                Mathf.Min(Screen.height - _mTransform.sizeDelta.y, Mathf.Max(0f, _mTransform.position.y)),
                _mTransform.position.z
                );
        }
    }
}